/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.biz.crawler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.yunji.framework_template.biz.crawler.in.TimesOfIndiaNewsContentImageHandler;
import com.yunji.framework_template.biz.service.NewsService;
import com.yunji.framework_template.common.enumeration.NewsType;
import com.yunji.framework_template.common.util.StringUtil;
import com.yunji.framework_template.common.web.Page;
import com.yunji.framework_template.orm.persistence.model.News;
import com.yunji.framework_template.orm.persistence.vo.ImageVO;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassName:NewsContentImageCrawler <br/>
 * Date: 2018年12月5日 上午10:49:20 <br/>
 * 
 * @author fenglibin1982@163.com
 * @Blog http://blog.csdn.net/fenglibing
 * @version
 * @see
 */
@Slf4j
public abstract class NewsContentImageCrawler extends Crawler {

    @Resource
    private NewsService                          newsService;
    @Resource
    private TimesOfIndiaNewsContentImageHandler  timesOfIndiaNewsContentImageHandler;
    /**
     * 存放所有内容中图片爬虫的List，应用启动的时候初使化值
     */
    private static List<NewsContentImageCrawler> newsContentImageCrawlerList = new ArrayList<NewsContentImageCrawler>();

    /**
     * 内容中图片提取爬虫的实现MAP
     * 
     * @return
     */
    public abstract Map<NewsType, ContentImageHandler> getContentImageHandleMap();

    private String getContentImage(News news) {
        if (news == null) {
            log.error("The news object is null");
            return null;
        }
        NewsType newsType = NewsType.getNewsType(news.getId());
        if (newsType == null) {
            return null;
        }
        ContentImageHandler handler = getContentImageHandleMap().get(newsType);
        if (handler == null) {
            log.error("Cannot get content image handler by news type:" + newsType);
            return null;
        }
        return handler.getImage(news.getUrl());
    }

    /**
     * 给新闻内容没有图片的新闻获取图片
     */
    public void getContentImage() {
        if (getContentImageHandleMap().size() == 0) {
            log.warn("No content image handler.");
            return;
        }
        NewsType[] newsTypeArr = NewsType.values();
        for (NewsType newsType : newsTypeArr) {
            ContentImageHandler handler = getContentImageHandleMap().get(newsType);
            if (handler == null) {// 没有对应的实现类就不处理
                // 使用默认的图片截图获取试试
                handler = timesOfIndiaNewsContentImageHandler;
                // continue;
            }
            // 拼装了新闻类型条件和名称，用于利用现有的功能来实现该功能，就不用写新的方法了
            String newsTypeConditionName = newsType.name() + " where img is null or img=''";
            News news = new News();
            news.setNewsType(newsTypeConditionName);
            long totalCount = newsService.count(news);
            int currentPage = 1;
            Page<News> page = new Page<News>();
            page.setObj(news);
            long pageSize = page.getPageSize();
            while (true) {
                page = page.reverseDisplayCalculate(currentPage, totalCount);
                List<News> newsList = newsService.selectByPage(page);
                if (newsList != null) {
                    newsList.forEach(n -> {
                        updateNewsImage(n);
                    });
                }
                if (newsList == null || newsList.size() < pageSize) {
                    break;
                }
                currentPage++;
            }
        }
    }

    /**
     * 更新新闻的截图
     * 
     * @param news
     */
    private void updateNewsImage(News news) {
        try {
            if (!StringUtil.isEmpty(news.getImg())) {
                return;
            }
            String image = getContentImage(news);
            if (!StringUtil.isEmpty(image)) {
                news.setImg(image);
                List<ImageVO> imageVOList = getNewsImageList(news);
                if (checkImageMd5Exists(imageVOList)) {
                    return;
                }
                addImageWidthHeight(news, imageVOList);
                News updateNews = new News();
                updateNews.setId(news.getId());
                updateNews.setImg(news.getImg());
                newsService.updateByPrimaryKeySelective(updateNews);
            }
        } catch (Exception e) {
            log.error("Get news:" + news.getId() + " image exception happened.", e);
        }
    }

    public static List<NewsContentImageCrawler> getNewsContentImageCrawlerList() {
        return newsContentImageCrawlerList;
    }

}
